<script setup lang="ts">
import type { PointGroupDetail } from '@/types/symmetry'
import { formatItaSymbol, formatSeitz } from '@/utils/formatters'
import { renderInline } from '@/utils/katex'
import { InformationCircleIcon, StarIcon } from '@heroicons/vue/24/solid'
import { useI18n } from 'vue-i18n'

interface Props {
  group: PointGroupDetail
}

const props = defineProps<Props>()
const { t } = useI18n()

// 格式化数值，保留必要的小数位
const formatNumber = (val: number) => {
  if (Math.abs(val) < 1e-10) return '0'
  if (Math.abs(val - Math.round(val)) < 1e-6) return Math.round(val).toString()
  return parseFloat(val.toFixed(3)).toString()
}

// 格式化复数值为简洁形式
const formatComplex = (val: { real: number; imag: number }) => {
  const { real, imag } = val
  const threshold = 1e-10

  // 纯实数
  if (Math.abs(imag) < threshold) {
    return formatNumber(real)
  }

  // 纯虚数
  if (Math.abs(real) < threshold) {
    const imagStr = formatNumber(imag)
    if (imagStr === '1') return 'i'
    if (imagStr === '-1') return '-i'
    return `${imagStr}i`
  }

  // 复数
  const realStr = formatNumber(real)
  const imagVal = Math.abs(imag)
  const imagStr = formatNumber(imagVal)

  const sign = imag >= 0 ? '+' : '-'
  const iPart = imagStr === '1' ? 'i' : `${imagStr}i`

  return `${realStr}${sign}${iPart}`
}

// 格式化矩阵为 LaTeX（简洁格式）
const formatMatrix = (matrix: number[][] | { real: number; imag: number }[][]) => {
  if (!matrix || matrix.length === 0) return ''

  // 检查是否为整数矩阵
  const isIntMatrix = matrix.every(row => row.every(val => typeof val === 'number' && Number.isInteger(val)))

  let rows
  if (isIntMatrix) {
    // 整数矩阵：直接显示整数
    rows = matrix.map(row => row.join(' & ')).join(' \\\\ ')
  } else {
    // 复数矩阵：使用 formatComplex
    rows = matrix.map(row => row.map(val => (typeof val === 'number' ? val.toString() : formatComplex(val as { real: number; imag: number }))).join(' & ')).join(' \\\\ ')
  }

  return `\\begin{pmatrix} ${rows} \\end{pmatrix}`
}

// 格式化角度（直接显示弧度，保留3位小数）
const formatAngle = (angle: number | null | undefined) => {
  if (angle == null) return '-'
  return angle.toFixed(3)
}
</script>

<template>
  <div class="space-y-4">
    <div v-if="group.operations.length" class="w-full overflow-x-auto">
      <table class="table-zebra table [&_td]:text-center [&_th]:text-center">
        <thead>
          <tr>
            <th>ID</th>
            <th>{{ t('views.pointGroupDetail.operations.seitz') }}</th>
            <th>{{ t('views.pointGroupDetail.operations.itaSymbol') }}</th>
            <th>{{ t('views.pointGroupDetail.operations.coordinateTriplet') }}</th>
            <th>Det</th>
            <th>ω</th>
            <th>nx</th>
            <th>ny</th>
            <th>nz</th>
            <th>[O3]</th>
            <th>[SU2]</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="op in group.operations" :key="op.id">
            <!-- ID & Generator Indicator -->
            <td class="font-mono">
              <div class="relative inline-block">
                {{ op.id }}
                <StarIcon v-if="group.generators.includes(op.id)" class="text-warning absolute top-1/2 -right-4 size-3 -translate-y-1/2" />
              </div>
            </td>

            <!-- Seitz Symbol -->
            <td v-html="renderInline(formatSeitz(op.seitz))"></td>

            <!-- ITA Symbol -->
            <td v-html="renderInline(formatItaSymbol(op.itaSymbol))"></td>

            <!-- Coordinate Triplet -->
            <td v-html="renderInline(`(${op.coordinateTriplet})`)"></td>

            <!-- Det -->
            <td class="font-mono text-sm">
              {{ op.det !== undefined ? (op.det > 0 ? '+1' : '-1') : '-' }}
            </td>

            <!-- Angle -->
            <td class="font-mono text-xs">{{ formatAngle(op.angle) }}</td>

            <!-- Axis (nx, ny, nz) -->
            <td class="font-mono text-xs">{{ op.axis?.[0]?.toFixed(3) ?? '-' }}</td>
            <td class="font-mono text-xs">{{ op.axis?.[1]?.toFixed(3) ?? '-' }}</td>
            <td class="font-mono text-xs">{{ op.axis?.[2]?.toFixed(3) ?? '-' }}</td>

            <!-- [O3] 矩阵 -->
            <td v-html="renderInline(formatMatrix(op.matrix))"></td>

            <!-- [SU2] 矩阵 -->
            <td>
              <span v-if="op.su2" v-html="renderInline(formatMatrix(op.su2))"></span>
              <span v-else class="text-xs opacity-50">-</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 说明 -->
    <div class="alert">
      <InformationCircleIcon class="text-info size-5 shrink-0" />
      <div class="text-sm">
        <ul class="list-inside list-disc space-y-0.5 opacity-80">
          <li v-if="group.generators.length">
            <span class="inline-flex items-center gap-1">
              <StarIcon class="text-warning size-4" />
              <span>{{ t('views.pointGroupDetail.operations.generatorHint') }}</span>
            </span>
          </li>
          <li>{{ t('views.pointGroupDetail.matrices.info.o3') }}</li>
          <li>{{ t('views.pointGroupDetail.matrices.info.su2') }}</li>
          <li v-if="group.crystalSystem === 'trigonal'">
            {{ t('symmetry.coordinateSystem.title') }}:
            {{ t('symmetry.coordinateSystem.note') }}
          </li>
        </ul>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!group.operations.length" class="flex-center min-h-[200px] flex-col gap-4">
      <div class="text-4xl">📊</div>
      <p class="text-sm opacity-70">{{ t('views.pointGroupDetail.operations.noData') }}</p>
    </div>
  </div>
</template>
